package com.intelligent.ispc.core.repository.jdbc;

import com.intelligent.ispc.common.persistence.jdbc.JdbcDynamicFiltersUtil;
import com.intelligent.ispc.common.persistence.jdbc.JdbcPageable;
import com.intelligent.ispc.common.persistence.jdbc.JdbcPaginationTemplate;
import com.intelligent.ispc.core.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter on 15/11/24.
 */
@Repository
public class  UserDaoImpl extends JdbcDaoSupport implements UserDao {

    @Autowired
    public UserDaoImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }

    @Override
    public List<User> findAll() {
        return getJdbcTemplate().query("SELECT * FROM t_user", BeanPropertyRowMapper.newInstance(User.class));
    }

    @Override
    public JdbcPageable findAll(Map<String,Object> searchParams, String sortType, int pageSize, int pageNumber) {
        String sql="SELECT * FROM t_user";

        String queryPageSql = JdbcDynamicFiltersUtil.newInstance(sql).buildParams(searchParams).addSort(sortType, "asc").builder();

        JdbcPageable page = new JdbcPageable(pageSize, pageNumber);
        JdbcPaginationTemplate.newInstance(getJdbcTemplate()).findPage(queryPageSql, page, BeanPropertyRowMapper.newInstance(User.class));

        return page;
    }
}
